import { computedAsync, createGlobalState } from '@peng_kai/kit/libs/vueuse';
import type { UnwrapRef } from 'vue';

interface AsideState {
  open: 'full';
  closed: 'hidden' | 'simple';
  footprint: number | 'fit';
  mask: boolean;
}

/**
 *  管理侧边(左边)菜单栏的状态
 */
function useAsideMenu() {
  const bp = useAppBreakpoints();
  const state = computed<AsideState>(() => {
    return bp.ltTabletl
      ? { open: 'full', closed: 'hidden', footprint: 0, mask: true }
      : bp.ltLaptop
        ? { open: 'full', closed: 'simple', footprint: 56, mask: true }
        : { open: 'full', closed: 'simple', footprint: 'fit', mask: false };
  });
  const opened = ref(false);
  const mode = computedAsync(() => opened.value ? state.value.open : state.value.closed);
  const drawerOpened = computed(() => opened.value || mode.value !== 'hidden');

  const toggle = (val?: boolean) => {
    opened.value = val ?? !opened.value;
  };

  watchEffect(() => {
    opened.value = bp.laptop;
  });

  return reactive({ state, mode, opened, drawerOpened, toggle });
}

/**
 *  管理侧边(右边)内容栏的状态
 */
function useAsideContent() {
  const bp = useAppBreakpoints();
  const state = computed<AsideState>(() => {
    return bp.ltTablet
      ? { open: 'full', closed: 'hidden', footprint: 0, mask: true }
      : { open: 'full', closed: 'hidden', footprint: 'fit', mask: false };
  });
  const drawerOpened = ref(false);
  const type = ref<'notification' | 'battle' | 'leaderboard'>('notification');

  const toggle = (opened?: boolean, newType?: UnwrapRef<typeof type>) => {
    if (newType === undefined) {
      drawerOpened.value = opened ?? !drawerOpened.value;
    }
    else if (newType !== type.value) {
      drawerOpened.value = true;
      type.value = newType;
    }
    else {
      drawerOpened.value = opened ?? !drawerOpened.value;
    }
  };

  return reactive({ state, drawerOpened, type, toggle });
}

/**
 *  管理整个布局的状态
 */
export const useLayout = createGlobalState(() => {
  const asideMenu = useAsideMenu();
  const asideContent = useAsideContent();

  return {
    asideMenu,
    asideContent,
  };
});
